package priv.tuyou.system.serviceImpl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import priv.tuyou.bo.ZtreeNode;
import priv.tuyou.dao.IDao;
import priv.tuyou.exception.ServiceException;
import priv.tuyou.system.dao.ISystemMenuDao;
import priv.tuyou.system.po.SystemMenu;
import priv.tuyou.system.service.ISystemMenuService;

@Service
public class SystemMenuServiceImpl implements ISystemMenuService{

	@Resource
	protected IDao dao;
	@Resource
	protected ISystemMenuDao systemMenuDao;

	@Override
	public SystemMenu add(Long parent_id, String name, String url, String icon, int orderValue) throws ServiceException {
		
		SystemMenu menu = new SystemMenu();
		menu.setParent_id(parent_id);
		menu.setName(name);
		menu.setUrl(url);
		menu.setIcon(icon);
		menu.setOrderValue(orderValue);
		menu.setPath(getPath(menu));
		dao.save(menu);
		return menu;
	}

	@Override
	public SystemMenu update(long id, Long parent_id, String name, String url, String icon, int orderValue) throws ServiceException {
		
		//检验父节点是否存在
		if(parent_id != null){
			
			SystemMenu parent = dao.get(SystemMenu.class, parent_id);
			if(parent == null){
				
				throw new ServiceException("上级菜单不存在");
			}
		}
		
		SystemMenu menu = dao.get(SystemMenu.class, id);
		if(menu == null){
			
			throw new ServiceException("你要修改的菜单不存在");
		}
		
		menu.setParent_id(parent_id);
		menu.setName(name);
		menu.setUrl(url);
		menu.setIcon(icon);
		menu.setOrderValue(orderValue);
		menu.setCreateTime(new Date());
		dao.update(menu);
		return menu;
	}

	@Override
	public List<ZtreeNode> getHierarchy(Long parent_id) {
		
		List<SystemMenu> list = systemMenuDao.getChildren(parent_id);
		List<ZtreeNode> nodes = new ArrayList<ZtreeNode>(list.size());
		for(SystemMenu menu : list){
			
			List<SystemMenu> children = systemMenuDao.getChildren(menu.getId());
			ZtreeNode node = new ZtreeNode(menu.getId(), menu.getName(), children.size() > 0 ? true : false);
			nodes.add(node);
		}
		return nodes;
	}

	@Override
	public String getPath(SystemMenu menu) {
		
		Long parent_id = menu.getParent_id();
		if(parent_id == null){
			
			return menu.getId() + "";
		}
		
		SystemMenu parent = dao.get(SystemMenu.class, parent_id);
		if(parent == null){
			
			return menu.getId() + "";
		}
		return parent.getPath() + "," + menu.getId();
	}
}
